var $parentNode = window.parent.document;

function $childNode(name) {
    return window.frames[name]
}

// tooltips
// $('.tooltip-demo').tooltip({
//     selector: "[data-toggle=tooltip]",
//     container: "body"
// });

// 使用animation.css修改Bootstrap Modal
$('.modal').appendTo("body");

$('#audit').click(function () {
    // var tableName = window.parent.;//获取父页面的参数值
    const menu = window.parent.$('.J_menuItem');//父页面的方法
    for (let i = 0; i < menu.length; i++) {
        if(menu[i].childNodes[2]?.innerText === '月嫂入驻审核') {
            console.log('1')
            menu[i].click()
        }
    }
})

$('#audit2').click(function () {
    // var tableName = window.parent.;//获取父页面的参数值
    const menu = window.parent.$('.J_menuItem');//父页面的方法
    console.log(menu);
    for (let i = 0; i < menu.length; i++) {
        if(menu[i].childNodes[2]?.innerText === '用户需求列表') {
            menu[i].click()
        }
    }
})

// $("[data-toggle=popover]").popover();

//折叠ibox
$('.collapse-link').click(function () {
    var ibox = $(this).closest('div.ibox');
    var button = $(this).find('i');
    var content = ibox.find('div.ibox-content');
    content.slideToggle(200);
    button.toggleClass('fa-chevron-up').toggleClass('fa-chevron-down');
    ibox.toggleClass('').toggleClass('border-bottom');
    setTimeout(function () {
        ibox.resize();
        ibox.find('[id^=map-]').resize();
    }, 50);
});

//关闭ibox
$('.close-link').click(function () {
    var content = $(this).closest('div.ibox');
    content.remove();
});

//判断当前页面是否在iframe中
//if (top == this) {
//    var gohome = '<div class="gohome"><a class="animated bounceInUp" href="index.html?v=4.0" title="返回首页"><i class="fa fa-home"></i></a></div>';
//    $('body').append(gohome);
//}

//animation.css
function animationHover(element, animation) {
    element = $(element);
    element.hover(
        function () {
            element.addClass('animated ' + animation);
        },
        function () {
            //动画完成之前移除class
            window.setTimeout(function () {
                element.removeClass('animated ' + animation);
            }, 2000);
        });
}

//拖动面板
function WinMove() {
    var element = "[class*=col]";
    var handle = ".ibox-title";
    var connect = "[class*=col]";
    $(element).sortable({
            handle: handle,
            connectWith: connect,
            tolerance: 'pointer',
            forcePlaceholderSize: true,
            opacity: 0.8,
        })
        .disableSelection();
};


//编辑器新增的ajax上传图片函数
function sendFile(files, editor, $editable) {
    var formData = new FormData();
    formData.append("file", files[0]);
    $.ajax({
        data : formData,
        type : "POST",
        url : "/common/sysFile/upload",    // 图片上传出来的url，返回的是图片上传后的路径，http格式
        cache : false,
        contentType : false,
        processData : false,
        dataType : "json",
        success: function(data) {//data是返回的hash,key之类的值，key是定义的文件名
            $('.summernote').summernote('insertImage',data.data);
        },
        error:function(data){
            //console.log("data",data)
            alert("上传失败");
        }
    });
}

//计算带中文的字符串显示宽度
function lengthCN(message) {
    var strlenght = 0;
    var txtval = $.trim(message);
    for (var i = 0; i < txtval.length; i++) {
        if (isCN(txtval.charAt(i)) == true) {
            strlenght = strlenght + 1.8;
        } else {
            strlenght = strlenght + 1;
        }
    }
    return strlenght;
}
function isCN(str) {
	var regexCh = /[u00-uff]/;
	return !regexCh .test(str);
}

//预览图片
function preview(url) {
    layer.open({
        type: 1,
        title: '预览',
        closeBtn: 1,
        area: [ '800px', '800px' ],
        skin: 'layui-layer-nobg', //没有背景色
        shadeClose: true,
        offset: 't',
        content: '<img width="90%" src="'+url+'"/>'
    });
}


//通过文件路径截取名称
function subFileName(fileUrl) {
    if(fileUrl==null)return "";
    var index = fileUrl .lastIndexOf("\/");
    fileUrl  = fileUrl .substring(index + 1, fileUrl .length);
    return fileUrl
}

//表单退回
function returnInfo(prefix) {
    var rows = $('#exampleTable').bootstrapTable('getSelections'); // 返回所有选择的行，当没有选择的记录时，返回一个空数组
    if (rows.length == 0) {
        layer.msg("请选择要退回的数据");
        return;
    }
    var ids = new Array();
    // 遍历所有选择的行数据，取每条数据对应的ID
    $.each(rows, function (i, row) {
        ids[i] = row['id'];
    });
    layer.confirm("确认要退回选中的'" + rows.length + "'条数据吗?", {
        btn: ['确认退回'],
        btn1:function(){
            console.log("yes");
            $.ajax({
                type: 'POST',
                data: {
                    "ids": ids
                },
                url: prefix + '/review',
                success: function (r) {
                    if (r.code == 0) {
                        layer.msg(r.msg);
                        reLoad();
                    } else {
                        layer.msg(r.msg);
                    }
                }
            });
        }
    });
}

//批量审核
function examine(prefix) {
    var rows = $('#exampleTable').bootstrapTable('getSelections'); // 返回所有选择的行，当没有选择的记录时，返回一个空数组
    if (rows.length == 0) {
        layer.msg("请选择要审核的数据");
        return;
    }
    var ids = new Array();
    // 遍历所有选择的行数据，取每条数据对应的ID
    $.each(rows, function (i, row) {
        ids[i] = row['id'];
    });
    layer.confirm("确认要审核选中的'" + rows.length + "'条数据吗?", {
        btn: ['通过', '不通过'],
        btn1:function(){
            console.log("yes");
            $.ajax({
                type: 'POST',
                data: {
                    "ids": ids,
                    state:1,
                    remark:""
                },
                url: prefix + '/review',
                success: function (r) {
                    if (r.code == 0) {
                        layer.msg(r.msg);
                        reLoad();
                    } else {
                        layer.msg(r.msg);
                    }
                }
            });
        },
        btn2:function(pass, index){
            layer.prompt({title: '请对这' + rows.length + '条数据填写未通过意见，并确认：', formType: 2}, function(remark, index){
                console.log("pass",remark);
                $.ajax({
                    type: 'POST',
                    data: {
                        "ids": ids,
                        state:2,
                        remark:remark
                    },
                    url: prefix + '/review',
                    success: function (r) {
                        if (r.code == 0) {
                            layer.msg(r.msg);
                            reLoad();
                        } else {
                            layer.msg(r.msg);
                        }
                    }
                });
                layer.closeAll();

            });
            return  false
    }
    });
}

//下载导入模板
function downExcelModel(table) {
    layer.confirm('您确定要下载导入模板吗？', {
        btn1:function(index){
            window.location.href = table;
            layer.close(index)
    }
    });
}


//导入
function importExcel(fileObj, formObj,cbatchId,orgId,url) {
    if (cbatchId==null||cbatchId==''){
        layer.msg('请选择认证批次后导入!');
    }else {
        var fileUrl = fileObj.val();
        var suffix = fileUrl.substr(fileUrl.lastIndexOf(".")).toLowerCase();//获得文件后缀名
        if (suffix == '.xls' || suffix == '.xlsx') {
            if (fileUrl) {
                formObj.ajaxSubmit({
                    type: "post",
                    url: url,
                    data: {cbatchId: cbatchId,orgId:orgId},
                    dataType: "json",
                    success: function (data) {
                        console.log("data",data);
                        if (data.code == 0) {
                            layer.msg(data.msg);
                            $('#exampleTable').bootstrapTable('refresh');
                        } else if (data.code ==41304 ) {
                            layer.confirm('是否下载错误报告？', {
                                btn1:function(index){
                                    window.location.href = '/jzweb/stuSignUp/importError';
                                    layer.close(index)
                                }
                            });
                        } else{
                            layer.msg(data.msg);
                        }
                    }, error: function (XMLHttpRequest, textStatus, errorThrown) {
                        console.log(XMLHttpRequest, textStatus, errorThrown)
                        layer.msg('出错了!');
                    }
                });
            } else {
                layer.msg('上传的文件不可为空');
                // parent.$.messager.alert('警告', "上传的文件不可为空", 'warning');
            }
        } else {
            layer.msg('请上传正确的Excel表格!');
            // $.messager.alert('警告', "", 'warning');
        }
    }
}


function AjaxPost(url,params){
    return new Promise(function (resolve,reject){
        layer.load(1);
        $.ajax({
            url: url,
            type: 'post',
            data: JSON.stringify(params) || '',
            contentType: 'application/json',
            success:function (data){
                if( data.code == 0 ){
                    layer.closeAll()
                    resolve(data);
                    return false;
                }else{
                    layer.msg('请检查接口返回状态码')
                    layer.closeAll()
                    reject(data)
                    return false;
                }

            },
            error:function (error){
                setTimeout( () => layer.closeAll(),3000)
                reject('请求失败，请检查网络',error)
            }
        })
    })
}

function AjaxGet(url,params){
    return new Promise(function (resolve,reject){
        layer.load(1);
        $.ajax({
            url: url,
            type: 'get',
            data: params || '',
            contentType: 'application/json',
            success:function (data){
                if( data.code == 0 ){
                    resolve(data);
                    layer.closeAll();
                    return false;
                }else{
                    layer.msg('请检查接口返回状态码')
                    return false;
                }

            },
            error:function (error){
                setTimeout( () => layer.closeAll(),3000)
                reject('请求失败，请检查网络',error)
            }
        })
    })
}

//设置select
function selectInput(myNode,size){
    let mydl=myNode.next().find('.layui-anim-upbit')
    let input=myNode.next().find('.layui-select-title').find('input')

    let myi =document.createElement('i')
    myi.className="layui-icon layui-icon-clear myi"
    myi.style="display:none";
    myNode.next().find('.layui-select-title').append(myi)

    let myinput=myNode.next().find('input')

    let mydd=mydl.find('dd')
    mydl.css('max-height','36'*(mydd.length<size?(mydd.length+2):(size+1))+'px');
    mydl.css('height','36'*(mydd.length<size?(mydd.length+2):(size+1))+'px');
    //分页设置
    let totle=mydd.length,page=1,isseach=false;
    let pageSum=Math.ceil( totle/ size);
    let oldpageSum=pageSum, oldepage=page;

    //全部隐藏
    const addHidden=()=>{
        mydd.each((index)=>{
            mydd[index].classList.add("hidden")
        })
    }
    addHidden()
    //获取数据
    const gethtml= async (page,size)=>{
        //去除前
        await addHidden()
        //这个地方要考虑搜索
        let hideList=mydl.find('dd.layui-hide')
        setTimeout(()=>{
            if(hideList.length>0){
                let num=0
                mydd.each(index=>{
                    if(mydd[index].className.indexOf('layui-hide')<0){
                        num++;
                        if(num>=(page-1)*size && num<size*page){
                            mydd[index].classList.remove('hidden')
                        }
                    }
                })

            }else{
                for (let i = (page-1)*size; i < size*page; i++) {
                    mydd[i]?.classList.remove('hidden')
                }
            }
            //判断是不是
            if(!mydl[0].querySelector('div.mydivSelect')){
                mydl[0].appendChild(getPageSize())
            }else{
                //修改page
                mydl[0].querySelector('span.mydivSelectSpan1').textContent =`第${page}页(共${pageSum}页)`
            }
        },200)
    }
    //分页
    const getPageSize=()=>{
        var div = document.createElement("div");
        div.className='mydivSelect'
        div.style.width='100%'
        div.style.height='30px'
        div.style.position='absolute'
        div.style.bottom='0'
        div.style.display='flex'
        div.style.styleflexDirection='row'
        div.style.stylealignItems='center'
        div.style.justifyContent='center'

        var pre=document.createElement("button")
        pre.textContent =`上一页`
        pre.style.margin= '0 10px'
        pre.style.border= '0'
        pre.style.background='transparent'
        pre.addEventListener('click',(evl)=>{
            evl.stopPropagation();
            evl.preventDefault();
            if(page>1){
                page=page-1
                gethtml(page,size)
            }
        })

        var span1=document.createElement("span");
        span1.textContent =`第${page}页(共${pageSum}页)`
        span1.className='mydivSelectSpan1'
        span1.style.lineHeight='30px';
        var nex=document.createElement("button")
        nex.textContent =`下一页`
        nex.style.margin= '0 10px'
        nex.style.border= '0'
        nex.style.background='transparent'
        nex.addEventListener('click',(evl)=>{
            evl.stopPropagation();
            evl.preventDefault();
            if((page+1)<=pageSum){
                page=page+1
                gethtml(page,size)
            }
        })

        div.appendChild(pre)
        div.appendChild(span1)
        div.appendChild(nex)
        return div
    }

    gethtml(page,size)

    //输入框监听
    myinput[0].addEventListener('input',async (data)=>{
        let inputvalue=$(myinput[0]).val()
        if(null==inputvalue||''==inputvalue){
            page=oldepage
            pageSum=oldpageSum
            gethtml(page,size)
            isisseach=false
            myi.style="display:none;"
        }else{
            myi.style="display:block;"
            await addHidden()
            isseach=true
            //等待
            setTimeout(()=>{
                mydd=mydl.find('dd')
                //首先得到所有其他的
                let newtotal=0
                mydd.each(index=>{
                    if(mydd[index].className.indexOf('layui-hide')<0){
                        newtotal++;
                        //要考虑分页
                        if(newtotal<=size){
                            mydd[index].classList.remove('hidden')
                        }
                    }
                })
                // //记录老的
                oldpageSum=pageSum
                oldepage=page
                page=1
                pageSum=Math.ceil( newtotal/ size)
                //修改分页的内容
                mydl[0].querySelector('span.mydivSelectSpan1').textContent =`第${page}页(共${pageSum}页)`
            },200)

        }


    })
    myinput[0].addEventListener('click',()=>{
        //清空
        setTimeout(()=>{
            if(isseach){
                //得到目前选中的范围,也就是page
                let inputvalue=$(myinput[0]).val(),pageindex=0;
                mydd.each(index=>{
                    if(mydd[index].innerHTML==inputvalue){
                        pageindex=index
                    }
                })
                //判断page位置
                let number=1;
                while (pageindex>=number*size){
                    number++;
                }
                page=number
                pageSum=Math.ceil( totle/ size)
                gethtml(page,size)
            }
        },100)

    })
    myinput[0].addEventListener('focus',()=>{
        myi.style=$(myinput[0]).val()!=''?"display:block":"display:none";
    })
    myinput[0].addEventListener('blur',()=>{
        setTimeout(()=>{
            myi.style="display:none";
        }, 300);
    })
    $("body").on('click', '.myi', function () {
        $(myinput[0]).val("")
        myi.style="display:none";
    });
}

function Enum(baseEnum) {
    return new Proxy(baseEnum, {
        get(target, name) {
            if (!baseEnum.hasOwnProperty(name)) {
                throw new Error(`"${name}"值不存在`)
            }
            return baseEnum[name]
        },
        set(target, name, value) {
            throw new Error('不能修改')
        }
    })
}

//富文本
function setWangeditor(editor,toolba,myHtml,placeholder,myOnChage,doSomething=null) {
    const {createEditor, createToolbar} = window.wangEditor
    const editorConfig = {
        placeholder,
        MENU_CONF: {
            uploadImage: {
                fieldName: 'file',
                server: '',
                // 自定义上传
                async customUpload(file, insertFn) {
                    var formData = new FormData();
                    formData.append('file', file);
                    //文件上传
                    await $.ajax({
                        cache: false,
                        async: true,
                        processData: false,
                        contentType: false,
                        type: "POST",
                        url: "/common/sysFile/upload",
                        data: formData,
                        error: (request) => {
                            parent.layer.alert("Connection error");
                        },
                        success: (res) => {
                            if (res.code == 0) {
                                // 最后插入图片
                                insertFn(res.data, '', '')
                            } else {
                                parent.layer.alert(res.msg)
                            }

                        }
                    });
                }
                // base64LimitSize: 10 * 1024 * 1024 // 10M 以下插入 base64
            },
            uploadVideo: {
                fieldName: 'file',
                server: '',
                // 自定义上传
                async customUpload(file, insertFn) {
                    var formData = new FormData();
                    formData.append('file', file);
                    //文件上传
                    await $.ajax({
                        cache: false,
                        async: true,
                        processData: false,
                        contentType: false,
                        type: "POST",
                        url: "/common/sysFile/upload",
                        data: formData,
                        error: (request) => {
                            parent.layer.alert("Connection error");
                        },
                        success: (res) => {
                            if (res.code == 0) {
                                // 最后插入视频
                                insertFn(res.data, '')
                            } else {
                                parent.layer.alert(res.msg)
                            }

                        }
                    });
                }
            }
        },
        onChange(editor) {
            myOnChage(editor)
        }
    }

    let myEditor = createEditor({
        selector: editor,
        html: '',
        config: editorConfig,
        mode: 'default', // or 'simple'
    })

    const toolbarConfig = {
        toolbarKeys: [
            "headerSelect",
            "blockquote",
            "|",
            "bold",
            "underline",
            "italic",
            {
                "key": "group-more-style",
                "title": "更多",
                "iconSvg": "<svg viewBox=\"0 0 1024 1024\"><path d=\"M204.8 505.6m-76.8 0a76.8 76.8 0 1 0 153.6 0 76.8 76.8 0 1 0-153.6 0Z\"></path><path d=\"M505.6 505.6m-76.8 0a76.8 76.8 0 1 0 153.6 0 76.8 76.8 0 1 0-153.6 0Z\"></path><path d=\"M806.4 505.6m-76.8 0a76.8 76.8 0 1 0 153.6 0 76.8 76.8 0 1 0-153.6 0Z\"></path></svg>",
                "menuKeys": [
                    "through",
                    "code",
                    "sup",
                    "sub",
                    "clearStyle"
                ]
            },
            "color",
            "bgColor",
            "|",
            "fontSize",
            "fontFamily",
            "lineHeight",
            "|",
            "bulletedList",
            "numberedList",
            "todo",
            {
                "key": "group-justify",
                "title": "对齐",
                "iconSvg": "<svg viewBox=\"0 0 1024 1024\"><path d=\"M768 793.6v102.4H51.2v-102.4h716.8z m204.8-230.4v102.4H51.2v-102.4h921.6z m-204.8-230.4v102.4H51.2v-102.4h716.8zM972.8 102.4v102.4H51.2V102.4h921.6z\"></path></svg>",
                "menuKeys": [
                    "justifyLeft",
                    "justifyRight",
                    "justifyCenter",
                    "justifyJustify"
                ]
            },
            {
                "key": "group-indent",
                "title": "缩进",
                "iconSvg": "<svg viewBox=\"0 0 1024 1024\"><path d=\"M0 64h1024v128H0z m384 192h640v128H384z m0 192h640v128H384z m0 192h640v128H384zM0 832h1024v128H0z m0-128V320l256 192z\"></path></svg>",
                "menuKeys": [
                    "indent",
                    "delIndent"
                ]
            },
            "|",
            // "emotion",
            "insertLink",
            {
                "key": "group-image",
                "title": "图片",
                "iconSvg": "<svg viewBox=\"0 0 1024 1024\"><path d=\"M959.877 128l0.123 0.123v767.775l-0.123 0.122H64.102l-0.122-0.122V128.123l0.122-0.123h895.775zM960 64H64C28.795 64 0 92.795 0 128v768c0 35.205 28.795 64 64 64h896c35.205 0 64-28.795 64-64V128c0-35.205-28.795-64-64-64zM832 288.01c0 53.023-42.988 96.01-96.01 96.01s-96.01-42.987-96.01-96.01S682.967 192 735.99 192 832 234.988 832 288.01zM896 832H128V704l224.01-384 256 320h64l224.01-192z\"></path></svg>",
                "menuKeys": [
                    "insertImage",
                    "uploadImage"
                ]
            },
            {
                "key": "group-video",
                "title": "视频",
                "iconSvg": "<svg viewBox=\"0 0 1024 1024\"><path d=\"M981.184 160.096C837.568 139.456 678.848 128 512 128S186.432 139.456 42.816 160.096C15.296 267.808 0 386.848 0 512s15.264 244.16 42.816 351.904C186.464 884.544 345.152 896 512 896s325.568-11.456 469.184-32.096C1008.704 756.192 1024 637.152 1024 512s-15.264-244.16-42.816-351.904zM384 704V320l320 192-320 192z\"></path></svg>",
                "menuKeys": [
                    "insertVideo",
                    "uploadVideo"
                ]
            },
            "insertTable",
            "codeBlock",
            "divider",
            "undo",
            "redo",
            "fullScreen"
        ]
    }
    const toolbar = createToolbar({
        editor: myEditor,
        selector: toolba,
        config: toolbarConfig,
        mode: 'default', // or 'simple'
    })
    myEditor.setHtml(myHtml)
    let isfullScreen=myEditor.isFullScreen
    setTimeout(()=>{
        $(toolba).find("button[data-menu-key='fullScreen']")?.on('click', function(event) {
            isfullScreen=!isfullScreen
            // 这里是你的新点击事件逻辑
            if(isfullScreen){
                $(toolba).parent().attr('style',`position: fixed;  top: 0;
                    left: 0;  width: 100%;   height: 100%;  margin: 0; z-index: 1000;`)
            }else{
                setTimeout(()=>{
                     $(toolba).parent().attr('style','')
                },200)
            }
        });
        $(editor).attr('style',`height: calc(100% - ${$(toolba)[0].clientHeight}px)`)
    },200)
    if(doSomething){
        doSomething(myEditor)
    }
}